﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Principal;

namespace Flash.Internal
{
    internal static class Helpers
    {
        internal static bool IsValidJSVariableName(this string str)
        {
            return Regex.IsMatch(str, "^[_$a-z]+[_$a-z0-9]*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        }

        internal static bool CheckPrincipalAgainstRules(IPrincipal user, IEnumerable<AccessRuleAttribute> rules)
        {
            bool allowedUser = false;
            bool allowedRole = false;
            bool denied = false;

            if (user.Identity.IsAuthenticated)
            {
                foreach (var rule in rules)
                {
                    if (rule.RuleType == AccessRuleType.AllowUser && (rule.Value == "*" || rule.Value == user.Identity.Name))
                    {
                        allowedUser = true;
                    }
                    else if (rule.RuleType == AccessRuleType.AllowRole && user.IsInRole(rule.Value))
                    {
                        allowedRole = true;
                    }
                    else if (rule.RuleType == AccessRuleType.DenyUser && (rule.Value == "*" || rule.Value == user.Identity.Name))
                    {
                        denied = true;
                    }
                    else if (rule.RuleType == AccessRuleType.DenyRole && user.IsInRole(rule.Value))
                    {
                        denied = true;
                    }
                }
            }
            else
            {
                foreach (var rule in rules)
                {
                    if (rule.RuleType == AccessRuleType.AllowUser && (rule.Value == "?" || rule.Value == "*"))
                    {
                        allowedUser = true;
                    }
                    else if (rule.RuleType == AccessRuleType.DenyUser && (rule.Value == "?" || rule.Value == "*"))
                    {
                        denied = true;
                    }
                }
            }

            return !denied && (allowedUser || allowedRole);
        }
    }
}
